<template>
  <div class="panel author-info-panel">
    <div class="panel-header">
      <i class="fas fa-user-circle" />
      <span>{{ isLogin ? '个人信息' : '关于作者' }}</span>
    </div>

    <!-- 未登录时显示站主信息 -->
    <div v-if="!isLogin">
      <!-- 站主基本信息 -->
      <div class="author-profile">
        <div class="author-avatar">
          <img :src="siteOwnerInfo.avatar" :alt="siteOwnerInfo.name" />
          <div class="online-indicator online"></div>
        </div>
        <div class="author-basic">
          <h3 class="author-name">{{ siteOwnerInfo.name }}</h3>
          <p class="author-title">{{ siteOwnerInfo.title }}</p>
          <div class="author-stats">
            <div class="stat-item">
              <span class="stat-value">{{ siteOwnerInfo.articleCount }}</span>
              <span class="stat-label">文章</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ formatNumber(siteOwnerInfo.followers) }}</span>
              <span class="stat-label">粉丝</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ formatNumber(siteOwnerInfo.views) }}</span>
              <span class="stat-label">阅读</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 站主简介 -->
      <div class="author-bio">
        <p>{{ siteOwnerInfo.bio }}</p>
      </div>

      <!-- 社交媒体 -->
      <div class="social-links">
        <div class="section-title">
          <i class="fas fa-share-alt" />
          社交媒体
        </div>
        <div class="social-grid">
          <a
            v-for="social in siteOwnerInfo.socialLinks"
            :key="social.name"
            :href="social.url"
            :title="social.name"
            class="social-link"
            target="_blank"
            rel="noopener noreferrer"
          >
            <i :class="social.icon" :style="{ color: social.color }" />
          </a>
        </div>
      </div>

      <!-- 站主成就 -->
      <div class="achievements-section">
        <div class="section-title">
          <i class="fas fa-trophy" />
          作者成就
        </div>
        <div class="achievements-grid">
          <div
            v-for="achievement in siteOwnerInfo.achievements"
            :key="achievement.id"
            class="achievement-badge"
            :title="achievement.description"
          >
            <div class="badge-icon" :style="{ backgroundColor: achievement.color }">
              <i :class="achievement.icon" />
            </div>
            <span class="badge-name">{{ achievement.name }}</span>
          </div>
        </div>
      </div>

      <!-- 联系方式 -->
      <div class="contact-section">
        <div class="section-title">
          <i class="fas fa-envelope" />
          联系作者
        </div>
        <div class="contact-list">
          <div class="contact-item" @click="copyToClipboard(siteOwnerInfo.email)">
            <i class="fas fa-envelope" />
            <span>{{ siteOwnerInfo.email }}</span>
            <i class="fas fa-copy copy-icon" />
          </div>
          <div v-if="siteOwnerInfo.github" class="contact-item">
            <i class="fab fa-github" />
            <a :href="siteOwnerInfo.github" target="_blank">{{ siteOwnerInfo.github.replace('https://', '') }}</a>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="followAuthor">
          <i class="fas fa-plus" />
          {{ isFollowing ? '已关注' : '关注作者' }}
        </el-button>
        <el-button size="small" @click="viewAuthorProfile">
          <i class="fas fa-user" />
          主页
        </el-button>
      </div>
    </div>

    <!-- 已登录时显示用户信息 -->
    <div v-else>
      <!-- 用户基本信息 -->
      <div class="author-profile">
        <div class="author-avatar">
          <img :src="userInfo.avatar || '/static/img/default-avatar.jpg'" :alt="userInfo.username" />
          <div class="online-indicator" :class="{ online: userInfo.isOnline }"></div>
        </div>
        <div class="author-basic">
          <h3 class="author-name">{{ userInfo.nickname || userInfo.username }}</h3>
          <p class="author-title">{{ getUserTitle(userInfo) }}</p>
          <div class="author-stats">
            <div class="stat-item">
              <span class="stat-value">{{ userInfo.articleCount || 0 }}</span>
              <span class="stat-label">文章</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ formatNumber(userInfo.followers || 0) }}</span>
              <span class="stat-label">粉丝</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ formatNumber(userInfo.views || 0) }}</span>
              <span class="stat-label">阅读</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户个人简介 -->
      <div class="author-bio">
        <p>{{ userInfo.bio || '这个人很懒，还没有写个人简介...' }}</p>
      </div>

      <!-- 用户技能 -->
      <div v-if="userInfo.skills && userInfo.skills.length > 0" class="skills-section">
        <div class="section-title">
          <i class="fas fa-code" />
          我的技能
        </div>
        <div class="skills-cloud">
          <span
            v-for="skill in userInfo.skills"
            :key="skill.name"
            class="skill-tag"
            :class="{ 'expert': skill.level === 'expert', 'advanced': skill.level === 'advanced' }"
          >
            {{ skill.name }}
            <span v-if="skill.level" class="skill-level">{{ getSkillLevelText(skill.level) }}</span>
          </span>
        </div>
      </div>

      <!-- 账户信息 -->
      <div class="account-section">
        <div class="section-title">
          <i class="fas fa-user-cog" />
          账户信息
        </div>
        <div class="account-info">
          <div class="info-item">
            <span class="info-label">用户名</span>
            <span class="info-value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">注册时间</span>
            <span class="info-value">{{ formatDate(userInfo.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">最后登录</span>
            <span class="info-value">{{ formatTime(userInfo.lastLoginTime) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">用户等级</span>
            <span class="info-value level-badge" :class="`level-${userInfo.level || 1}`">
              {{ getUserLevel(userInfo.level || 1) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="editProfile">
          <i class="fas fa-edit" />
          编辑资料
        </el-button>
        <el-button size="small" @click="viewUserProfile">
          <i class="fas fa-user" />
          我的主页
        </el-button>
      </div>

      <!-- 快捷功能 -->
      <div class="quick-actions">
        <div class="section-title">
          <i class="fas fa-bolt" />
          快捷功能
        </div>
        <div class="quick-actions-grid">
          <div class="quick-action-item" @click="goToCreateBlog">
            <i class="fas fa-pen-fancy" />
            <span>写文章</span>
          </div>
          <div class="quick-action-item" @click="goToMyArticles">
            <i class="fas fa-file-alt" />
            <span>我的文章</span>
          </div>
          <div class="quick-action-item" @click="goToFavorites">
            <i class="fas fa-star" />
            <span>我的收藏</span>
          </div>
          <div class="quick-action-item" @click="goToSettings">
            <i class="fas fa-cog" />
            <span>设置</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

const router = useRouter();
const userStore = useUserStore();

const isFollowing = ref(false);

// 登录状态
const isLogin = computed(() => userStore.isLogin());

// 站主信息（固定的静态数据）
const siteOwnerInfo = ref({
  name: '张三',
  title: '全栈开发工程师',
  avatar: '/static/img/author-avatar.jpg',
  bio: '热爱技术，专注于Web开发和用户体验设计。分享技术心得，记录学习历程。',
  articleCount: 156,
  followers: 2340,
  views: 45678,
  email: 'author@example.com',
  github: 'https://github.com/author',
  socialLinks: [
    { name: 'GitHub', icon: 'fab fa-github', color: '#333', url: 'https://github.com/author' },
    { name: 'Twitter', icon: 'fab fa-twitter', color: '#1da1f2', url: 'https://twitter.com/author' },
    { name: 'LinkedIn', icon: 'fab fa-linkedin', color: '#0077b5', url: 'https://linkedin.com/in/author' },
    { name: '掘金', icon: 'fas fa-book', color: '#1e80ff', url: 'https://juejin.cn/user/author' }
  ],
  achievements: [
    {
      id: 1,
      name: '优质作者',
      icon: 'fas fa-star',
      color: '#f59e0b',
      description: '连续3个月获得优质作者认证'
    },
    {
      id: 2,
      name: '技术达人',
      icon: 'fas fa-code',
      color: '#3b82f6',
      description: '发布技术文章超过100篇'
    },
    {
      id: 3,
      name: '活跃贡献者',
      icon: 'fas fa-heart',
      color: '#ef4444',
      description: '获得超过1000个点赞'
    },
    {
      id: 4,
      name: '知识分享者',
      icon: 'fas fa-share',
      color: '#10b981',
      description: '帮助超过1000名开发者'
    }
  ]
});

// 用户信息（从用户store获取）
const userInfo = computed(() => {
  return userStore.userInfo || {
    username: '',
    nickname: '',
    avatar: '',
    bio: '',
    articleCount: 0,
    followers: 0,
    views: 0,
    isOnline: false,
    createTime: new Date(),
    lastLoginTime: new Date(),
    level: 1,
    skills: []
  };
});

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  }
  return num.toString();
};

// 获取技能等级文本
const getSkillLevelText = (level: string) => {
  const levels = {
    expert: '精通',
    advanced: '熟练',
    intermediate: '掌握'
  };
  return levels[level] || '';
};

// 获取用户标题
const getUserTitle = (user: any) => {
  if (user.articleCount > 100) return '资深作者';
  if (user.articleCount > 50) return '优秀作者';
  if (user.articleCount > 10) return '活跃作者';
  return '新晋作者';
};

// 获取用户等级
const getUserLevel = (level: number) => {
  const levels = [
    'Lv.1 新手',
    'Lv.2 初级',
    'Lv.3 中级',
    'Lv.4 高级',
    'Lv.5 专家',
    'Lv.6 大师'
  ];
  return levels[Math.min(level - 1, levels.length - 1)] || 'Lv.1 新手';
};

// 格式化时间
const formatTime = (time: Date | string | undefined) => {
  if (!time) return '未知时间';

  const date = typeof time === 'string' ? new Date(time) : time;

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return '无效时间';
  }

  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  return date.toLocaleDateString();
};

// 格式化日期
const formatDate = (time: Date | string | undefined) => {
  if (!time) return '未知时间';

  const date = typeof time === 'string' ? new Date(time) : time;

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return '无效日期';
  }

  return date.toLocaleDateString();
};

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('已复制到剪贴板');
  } catch (err) {
    ElMessage.error('复制失败，请手动复制');
  }
};

// 关注作者
const followAuthor = () => {
  if (!isLogin.value) {
    ElMessage.warning('请先登录后再关注作者');
    return;
  }
  isFollowing.value = !isFollowing.value;
  ElMessage.success(isFollowing.value ? '关注成功' : '已取消关注');
};

// 查看作者主页
const viewAuthorProfile = () => {
  router.push({ name: 'authorProfile', params: { authorId: 'site-owner' } });
};

// 编辑个人资料
const editProfile = () => {
  router.push({ name: 'profileEdit' });
};

// 查看我的主页
const viewUserProfile = () => {
  router.push({ name: 'userProfile', params: { userId: userInfo.value.id } });
};

// 快捷功能
const goToCreateBlog = () => {
  router.push({ name: 'blogCreate' });
};

const goToMyArticles = () => {
  router.push({ name: 'userArticles' });
};

const goToFavorites = () => {
  router.push({ name: 'userFavorites' });
};

const goToSettings = () => {
  router.push({ name: 'userSettings' });
};

// 监听登录状态变化，更新数据
watch(isLogin, (newValue) => {
  if (newValue) {
    // 用户登录后，可以获取用户详细数据
    userStore.getUserInfo().then(() => {
      // 可以在这里获取用户的详细统计数据
    });
  }
});

onMounted(() => {
  // 初始化时检查登录状态
  if (isLogin.value) {
    userStore.getUserInfo();
  }
});
</script>

<style scoped lang="scss">
.panel {
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
  font-size: 1rem;

  i {
    color: #f59e0b;
    font-size: 1.1rem;
  }
}

// 作者基本信息
.author-profile {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;

  .author-avatar {
    position: relative;
    width: 64px;
    height: 64px;
    border-radius: 50%;
    overflow: hidden;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .online-indicator {
      position: absolute;
      bottom: 2px;
      right: 2px;
      width: 14px;
      height: 14px;
      border-radius: 50%;
      background: #94a3b8;
      border: 2px solid white;

      &.online {
        background: #10b981;
        animation: pulse 2s infinite;
      }
    }
  }

  .author-basic {
    flex: 1;

    .author-name {
      font-size: 1.1rem;
      font-weight: 700;
      color: #1e293b;
      margin: 0 0 4px 0;
    }

    .author-title {
      font-size: 0.85rem;
      color: #64748b;
      margin: 0 0 12px 0;
    }

    .author-stats {
      display: flex;
      gap: 16px;

      .stat-item {
        text-align: center;

        .stat-value {
          display: block;
          font-size: 1rem;
          font-weight: 600;
          color: #1e293b;
        }

        .stat-label {
          font-size: 0.75rem;
          color: #94a3b8;
        }
      }
    }
  }
}

// 个人简介
.author-bio {
  background: #fef7e0;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 16px;
  border-left: 3px solid #f59e0b;

  p {
    font-size: 0.85rem;
    color: #92400e;
    line-height: 1.5;
    margin: 0;
  }
}

// 通用标题样式
.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.9rem;
  font-weight: 600;
  color: #475569;
  margin-bottom: 10px;

  i {
    font-size: 0.8rem;
    color: #f59e0b;
  }
}

// 社交媒体
.social-links {
  margin-bottom: 16px;

  .social-grid {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .social-link {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: #f8fafc;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s ease;

    &:hover {
      background: #e2e8f0;
      transform: translateY(-2px);
    }

    i {
      font-size: 1rem;
    }
  }
}

// 技能标签
.skills-section {
  margin-bottom: 16px;

  .skills-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .skill-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background: #f1f5f9;
    color: #64748b;
    border-radius: 12px;
    font-size: 0.75rem;
    border: 1px solid #e2e8f0;

    &.expert {
      background: #fee2e2;
      color: #dc2626;
      border-color: #fecaca;
    }

    &.advanced {
      background: #fef3c7;
      color: #d97706;
      border-color: #fde68a;
    }

    .skill-level {
      font-size: 0.65rem;
      opacity: 0.8;
    }
  }
}

// 成就徽章
.achievements-section {
  margin-bottom: 16px;

  .achievements-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .achievement-badge {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    padding: 8px;
    background: #f8fafc;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background: #e2e8f0;
      transform: translateY(-1px);
    }

    .badge-icon {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 0.9rem;
    }

    .badge-name {
      font-size: 0.7rem;
      color: #475569;
      text-align: center;
      line-height: 1.2;
    }
  }
}

// 账户信息
.account-section {
  margin-bottom: 16px;

  .account-info {
    background: #f8fafc;
    padding: 12px;
    border-radius: 8px;

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 0;
      font-size: 0.85rem;

      &:not(:last-child) {
        border-bottom: 1px solid #e2e8f0;
      }

      .info-label {
        color: #64748b;
        font-weight: 500;
      }

      .info-value {
        color: #1e293b;

        &.level-badge {
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 0.75rem;
          font-weight: 600;

          &.level-1 { background: #f1f5f9; color: #64748b; }
          &.level-2 { background: #dbeafe; color: #3b82f6; }
          &.level-3 { background: #d1fae5; color: #10b981; }
          &.level-4 { background: #fef3c7; color: #f59e0b; }
          &.level-5 { background: #fee2e2; color: #ef4444; }
          &.level-6 { background: #ede9fe; color: #8b5cf6; }
        }
      }
    }
  }
}

// 联系方式
.contact-section {
  margin-bottom: 16px;

  .contact-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .contact-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    background: #f8fafc;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.85rem;
    color: #475569;

    &:hover {
      background: #e2e8f0;
    }

    i {
      color: #64748b;
      font-size: 0.8rem;
      width: 16px;
    }

    span {
      flex: 1;
    }

    a {
      color: #3b82f6;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    .copy-icon {
      opacity: 0;
      transition: opacity 0.2s ease;
    }

    &:hover .copy-icon {
      opacity: 1;
    }
  }
}

// 操作按钮
.action-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;

  :deep(.el-button) {
    flex: 1;
    font-size: 0.8rem;

    &.el-button--small {
      padding: 6px 12px;
    }
  }
}

// 快捷功能
.quick-actions {
  .quick-actions-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .quick-action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px;
    background: #f8fafc;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.8rem;
    color: #475569;

    &:hover {
      background: #e2e8f0;
      transform: translateY(-1px);

      i {
        color: #f59e0b;
      }
    }

    i {
      font-size: 1.2rem;
      color: #64748b;
      transition: color 0.2s ease;
    }
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(16, 185, 129, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
  }
}
</style>